import 'dart:async';
import 'dart:collection';

class RequestScheduler {
  final _queue = Queue<Future Function()>();
  var _activeRequests = 0;
  final int maxConcurrent;
  final _completer = Completer<void>();
  
  RequestScheduler({this.maxConcurrent = 3});
  
  void addRequest(Future Function() request) {
    _queue.add(request);
    _processNext();
  }
  
  Future<void> get done => _completer.future;
  
  void _processNext() {
    while (_activeRequests < maxConcurrent && _queue.isNotEmpty) {
      _activeRequests++;
      final request = _queue.removeFirst();
      
      request().then((_) {
        _activeRequests--;
        _processNext();
      }).catchError((e) {
        _activeRequests--;
        _processNext();
        print('请求失败: $e');
      });
    }
    
    if (_activeRequests == 0 && _queue.isEmpty) {
      _completer.complete();
    }
  }
}

// // 使用示例
// void fetchWithScheduler() async {
//   final scheduler = RequestScheduler(maxConcurrent: 4);
//
//   for (int i = 0; i < 500; i++) {
//     scheduler.addRequest(() => _fetchItem(i));
//   }
//
//   await scheduler.done;
//   print('所有请求完成');
// }